import _ from 'lodash'

/**
 * 构建适配下面fillFilter函数的默认filter
 * @param key  表格列key
 * @param filterMultiple 是否支持多选
 * @param kwargs
 * @returns {{key: *, filterMultiple: boolean}}
 */
const defaultFilterConfigCreate = (
  key,
  filterMultiple = false,
  kwargs = {}
) => ({
  ...kwargs,
  key,
  filterMultiple
})
/**
 * 生成默认表格filters
 * @param dataSource 表格数据
 * @param columnKey  列ID
 * @returns {*}
 */
const defaultColumnFiltersCreator = (dataSource, columnKey) =>
  _.uniqWith(
    dataSource.map(item => ({
      label: item[columnKey] || '未指定',
      value: item[columnKey]
    })),
    _.isEqual
  )
/**
 * 生成默认表格filter判断函数
 * @param columnKey 列ID
 * @returns {function(*, *): boolean}
 */
const defaultColumnFilterMethodCreator = columnKey => (value, row) =>
  value === row[columnKey]
/**
 * 填充table filter属性
 * @param columns 原始table column
 * @param dataSource 表格数据
 * @param filterConfigs filter定义
 * [
 *  {
 *    'key':                      String,   Required  列
 *    'filterMultiple':           Boolean,
 *    'filterMethodCreator':     Function,
 *    'filtersCreator':          Function
 *  }
 * ]
 * eg:
 * [
 *  { 限制单选
 *    'key': 'name',
 *    'filterMultiple': false
 *  },
 *  { 支持多选
 *    'key': 'name',
 *    'filterMultiple': true,
 *    'filterMethodCreator': () => {},
 *    'filtersCreator': () => {}
 *  },
 *  { 自定义生成可选filters
 *    'key': 'name',
 *    'filterMultipleCreator': true,
 *    'filtersCreator': () => {}
 *  },
 *  { 自定义过滤判断方法
 *    'key': 'name',
 *    'filterMultipleCreator': true,
 *    'filterMethodCreator': () => {},
 *  }
 * ]
 * @returns {*}
 */
const fillColumnFilter = (columns, dataSource, filterConfigs = []) => {
  if (!dataSource) {
    dataSource = []
  }
  let cacheColumns = columns
  if (dataSource.length === 0) {
    return cacheColumns
  }

  const wrapColumns = config => {
    cacheColumns = cacheColumns.map(column => {
      if (column.key !== config.key) {
        return column
      }

      const getFilters = () =>
        _.get(config, 'filtersCreator', defaultColumnFiltersCreator)(
          dataSource,
          config.key
        )
      const getFilterMethods = () =>
        _.get(config, 'filterMethodCreator', defaultColumnFilterMethodCreator)(
          config.key
        )
      const getFilterMultiple = () => _.get(config, 'filterMultiple', false)

      return {
        ...column,
        filters: getFilters(),
        filterMultiple: getFilterMultiple(),
        filterMethod: getFilterMethods()
      }
    })
  }

  filterConfigs.forEach(wrapColumns)
  return cacheColumns
}

const defaultSorterMethod = (a, b, type) => {
  let result = true
  if (!isNaN(Number(a)) && !isNaN(Number(b))) {
    result = Number(a) > Number(b)
  } else {
    // 其他类型，如字符串，直接比较
    result = a > b
  }

  if (type === 'desc' || type === 'asc') {
    result = !result
  }
  return result ? 1 : -1
}

const fillColumnSorter = (columns, SorterConfigs = []) => {
  for (const column of columns) {
    if (!column.sortable || column.sortMethod) {
      continue
    }

    const sortConfig = _.find(SorterConfigs, { key: column.key })
    if (!sortConfig) {
      // 支持排序，没有特殊配置，则使用默认排序方法
      column.sortMethod = defaultSorterMethod
      continue
    }

    const { sortMethod = defaultSorterMethod } = sortConfig
    column.sortMethod = sortMethod
  }

  return columns
}

const getParams = (param) => {
  const { pageNum, pageSize, sorter } = param
  let params = {}
  if (JSON.stringify(sorter) === '{}' || sorter.order === 'normal') {
    params = { pageNum, pageSize }
  } else {
    // const sortField = _.snakeCase(sorter.field)
    const sortField = sorter.field
    const sortOrder = sorter.order
    params = { pageNum, pageSize, sortField, sortOrder }
  }
  return params
}

const filterTableData = (search, objs) => {
  const lowerSearch = search.toLowerCase()
  if (lowerSearch !== '') {
    return objs.filter(function (dataNews) {
      return Object.keys(dataNews).some(function (key) {
        return String(dataNews[key]).toLowerCase().indexOf(lowerSearch) > -1
      })
    })
  }
  return objs
}

export {
  fillColumnFilter,
  fillColumnSorter,
  defaultFilterConfigCreate,
  defaultSorterMethod,
  getParams,
  filterTableData
}
